(function(){
	
	function asyncRequest(o,callback){
		var xhr = new XMLHttpRequest();
			xhr.open(o.method,o.uri,true);
			xhr.onreadystatechange=function(){
				if(xhr.readyState==4){
					if(xhr.status==200){
						callback(xhr.responseText);
					}
					else{
						callback(false);
					}
				}
			}
			xhr.send();
		return xhr;
	}
	
	function ajaxQueue(){
		this.queue=[];
		this.retrycount=3;
		this.currentRetry=0;
		this.timout=6000;
		this.paused=false;
		this.conn={};
		this.timer={};
		this.onComplete=new Crawler.util.Observer;
		this.onFlush=new Crawler.util.Observer;
		this.onFailure=new Crawler.util.Observer;
	}
	
	ajaxQueue.prototype={
		add:function(o){
			this.queue.push(o);
		},
		dequeue:function(){
			this.queue.pop();
		},
		clear:function(){
			this.queue=[];
		},
		pause:function(){
			this.paused=true;
		},

		flush:function(){
			if(this.queue.length>0){
				return;
			}
			if(this.paused){
				this.paused=false;
				return;
			}
			var self = this;
			this.currentRetry++;
			var abort=function(){
				self.conn.abort();
				if(self.retryCount==self.currentRetry){
					self.onFailure.fire();
					self.currentRetry=0;
				}
				else{
					self.flush();
				}
			};
			this.timer=window.setTimout(abort,this.timeout);
			var callback=function(o){
				window.clearTimeout(self.timer);
				self.currentRetry=0;
				self.queue.shift();
				self.onFlush.fire(o);
				if(self.queue.length==0){
					self.onComplete.fire();
					return;
				}
				self.flush();
			};
			this.conn=asyncRequest(this.quque[0],callback);
		}
	};
	
	window.Crawler=window.Crawler||{};
	Crawler.ajaxQueue=ajaxQueue;
})();
